from random import shuffle


def title():
    print("smash the code for python".center(64, '*'))


def subtitle():
    print("~ 源自 iOS 经典解谜游戏 Smash the Code")


def tips():
    print("~ 目标是破解一个四位数的密码，每位数字(1~9)各不相同，用最少次数猜出")
    print("●：正确的数字出现在正确的位置的数量")
    print("○：正确的数字出现在错误的位置的数量")


def win():
    print("你赢了！")


def lost(code):
    print("你失去了所有机会！你寻找的代码是：{}".format(''.join(code)))


BLACK_PEG = '●'
WHITE_PEG = '○'

DIGITS = list("123456789")


def create_random_code():
    digits = DIGITS[:]
    shuffle(digits)
    return digits[:4]


def indicator(your_code, correct_code):
    black = 0
    white = 0

    for index, digit in enumerate(your_code):
        if digit in correct_code:
            white += 1
            
            if correct_code[index] == digit:
                black += 1
                white -= 1

    return black, white


def display_pegs(counter, black, white):
    placeholder = '□' * (4 - black - white)
    print("[{}]<<< {}{}{}".format(counter, BLACK_PEG * black, WHITE_PEG * white, placeholder))


def read_code(counter):
    while True:
        code = input("[{}]>>> ".format(counter))
        digits = list(code)

        if '0' not in code and code.isdigit() and len(set(digits)) == 4:
            return digits


def main():
    title()
    subtitle()
    tips()

    while True:
        counter = 1
        goal = create_random_code()
        print('~' * 64)

        while counter <= 10:
            code = read_code(counter)
            black, white = indicator(code, goal)
            display_pegs(counter, black, white)

            if black == 4:
                win()
                break

            counter += 1
        else:
            lost(goal)


if __name__ == '__main__':
    main()
